package com.imooc.distribution.vo;

import cn.hutool.core.date.DateUtil;
import com.imooc.distribution.constant.CouponStatus;
import com.imooc.distribution.constant.PeriodType;
import com.imooc.distribution.pojo.Coupon;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 优惠券模板分类工具实现
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class CouponClassify {

    private List<Coupon> usable;

    private List<Coupon> used;

    private List<Coupon> expired;

    /**
     * 对当前优惠券进行分类
     *
     * @param coupons
     * @return
     */
    public static CouponClassify classify(List<Coupon> coupons) {

        List<Coupon> usable = new ArrayList<>(coupons.size());
        List<Coupon> used = new ArrayList<>(coupons.size());
        List<Coupon> expired = new ArrayList<>(coupons.size());

        coupons.forEach(c -> {
            Boolean isTimeExpired;
            Long curTime = System.currentTimeMillis();
            //如果是固定如期
            final CouponTemplateSDK templateSDK = c.getTemplateSDK();
            log.debug("获取到的SDK:{}",templateSDK);
            if (templateSDK !=null &&templateSDK.getRule() != null) {
                final TemplateRule.Expiration expiration = templateSDK.getRule().getExpiration();
                if (PeriodType.REGULAR.getCode().equals(expiration.getPeriod())) {
                    isTimeExpired = expiration.getDeadLine()
                            <= curTime;
                }else {
                    isTimeExpired = DateUtil.offsetDay(
                            c.getAssignTime(),
                            expiration.getGap()
                    ).getTime() <= curTime;
                }
            }else{
                log.error("优惠劵规则不存在，无法领取优惠劵");

            return;

            }

            if (c.getStatus() == CouponStatus.USABLE) {
                usable.add(c);
            } else if (c.getStatus() == CouponStatus.USED) {
                used.add(c);
            } else {
                expired.add(c);
            }
        });
        return new CouponClassify(usable, used, expired);
    }
}
